
ab = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJLKMNOPQRSTUVWXYZ_0123456789+-*/%&|!~()^")
white = list("\r\n\t ")


def scan(s):
    stack = []
    tstack = []
    sacc = ""
    def f(sacc):
        if sacc in list("0123456789abcdef"):
            tstack.append(int(sacc, base=16))
        elif sacc in ["+", "-", "/", "if", "if-else", "while-do", "do-while", "over", "swap", "drop", "call", "load", "dump", "ext"]:
            tstack.append(sacc)
        else:
            raise Exception(f"未知词：{sacc}")
    for ch in s + "\0":
        if ch in ab:
            sacc += ch
        elif ch in white:
            if len(sacc) > 0:
                f(sacc)
                sacc = ""
        elif ch == "[":
            if len(sacc) > 0:
                f(sacc)
                sacc = ""
            stack.append(tstack)
            tstack = []
        elif ch == "]":
            if len(sacc) > 0:
                f(sacc)
                sacc = ""
            assert len(stack) > 0,  "括号不匹配"
            x = stack.pop()
            x.append(tstack)
            tstack = x
        elif ch == "\0":
            assert len(stack) == 0,  "括号不匹配"
            if len(sacc) > 0:
                f(sacc)
                sacc = ""
        else:
            raise Exception(f"未知字符：{ch, repr(ch)}")
    return tstack

def repr2(l, space=0):
    flag = 0
    for x in l:
        if isinstance(x, (int, float, str)):
            s = str(x)
            if flag == 0:
                print("  " * space + s, end="")
                flag = 1
            elif flag == 1:
                print(" " + s, end="")
            else:
                print("  " * space + s, end="")
                flag = 1
        else:
            if flag == 1 :
                print()
            repr2(x, space + 1)
            flag = 2
    else:
        print()




if __name__ == "__main__":
    s = """
    a
    [0 over]
    [
      1
        0 swap
        1 -
    ]
    while-do
    drop
    """
    repr2(scan(s))
    print()

